import {Component,OnInit,ChangeDetectorRef} from '@angular/core';
import { UpphotoService } from '../../../services/upphoto.service';
import { ActionSheetController,ModalController } from '@ionic/angular';
import { PopoverComponent } from '../../components/popover/popover.component';
import { NotarizationInfoService } from '../../../services/notarization-info.service';
import { HttpService } from '../../../services/http.service';
import { Router } from '@angular/router';
import { commService } from '../../../services/comm.service';
import { BaseUiService } from '../../../services/base-ui.service';
@Component({
  selector: 'app-updata',
  templateUrl: './updata.page.html',
  styleUrls: ['./updata.page.scss'],
})
export class UpdataPage implements OnInit {
  public imgList:any = []
  public orderId:any
  public updatalist = [];
  public newdatalist:any = []//去重后的材料列表
  public signatureImg:any //签字的图片
  public signatureId:any //签字的图片ID
  public isShow:boolean = true
  public matterId:any //公证事项ID
  public isShowimg = false;
  public pdfImglist = [];
  constructor(
    
    public commService: commService,
    public router: Router,
    public HttpService: HttpService,
    public NotarizationInfoService: NotarizationInfoService,
    public modalController: ModalController,
    public upphotoService:UpphotoService,
    public actionSheetController: ActionSheetController,
    public BaseUiService: BaseUiService,
    private cd: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.matterId = this.NotarizationInfoService.getNotayMatter()
    this.orderId = this.NotarizationInfoService.getOrder()
    this.seach()
  }




  //关闭萝卜图
  iconclick() {
    this.pdfImglist = []
    this.isShowimg = false
  }

  //根据ID获取到需要的材料
  seach(){
    let that = this;
    let arr = []
    this.matterId.forEach(element => {
      arr.push(element.notaryItemId)
    });
    let p = {
      unitGuid:arr.toString()
    }
    this.HttpService.getNotaryItem(p).then(res =>{
      if(res['code']==200){
        for(let item of  res['items']){
          let info = {
            materialName: item.name,
            annexFileLists:[],
            orderId: that.orderId,
            notaryItemId: item.notaryItemModelId
          }
          that.updatalist.push(info)
        }
        // this.updatalist = res['items']
        console.log(that.updatalist,'++++++123')
        let obj = {}
        for (var i = 0; i < res['items'].length; i++) {
          if (!obj[res['items'][i].name]) {
            this.newdatalist.push(res['items'][i]);
            obj[res['items'][i].name] = true;
            setTimeout(() => {
              this.cd.detectChanges();
            },200)
          }
        }
        console.log(this.newdatalist)
      }else{
        alert(res['msg'])
      }
    }).catch(err =>{
      alert(err)
    })
    console.log(this.updatalist,'++++++123')
  }
  //签字
  async presentPopover() {
    
    const modal = await this.modalController.create({
      component: PopoverComponent,
    });
    await modal.present();
    //监听销毁的事件，此时data存的是模态窗口页面销毁时候的值
    const{data}=await modal.onDidDismiss();
    this.signatureImg = data.result.msg
    if(data.result.info){
      this.upphotoService.Uploading(this.signatureImg).then(res =>{
        // this.signatureId = res[0]['filePath'];
        this.BaseUiService.showLoading('正在生成电子签名文件',0)
        let p = {
          unitGuid: this.orderId,
          signName: res[0]['filePath']
        }
        this.HttpService.doSetSignName(p).then(
          res => {
            this.BaseUiService.hideLoading();
            if(res['code'] == 200){
              this.router.navigate(['/transaction/topay'])
            }
          }
        )
      })
    }
  }
   //底部弹出
   async presentActionSheet(i:any) {
    const actionSheet = await this.actionSheetController.create({
      header: '上传材料',
      buttons: [ {
        text: '拍照上传',
        icon: 'camera',
        handler: () => {
          this.commService.photo(400,40).subscribe(res=>{
            console.log(res,'++666')
            this.demo(res,i)
          })
          
        }
      }, {
        text: '相册上传',
        icon: 'image-outline',
        handler: () => {
          this.commService.picture(300,40).subscribe(res =>{
            this.demo(res,i)
          })
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
          console.log('关闭');
        }
      }]
    });
    await actionSheet.present();
  }

  demo(info:any,i:any){
    let _this =this
    this.upphotoService.Uploading(info).then( res1 =>{
      // _this.imgList = [..._this.imgList,...res1]
      // _this.newdatalist[i].imgPath =  [..._this.newdatalist[i].imgPath,...res1]
      if(this.newdatalist[i].imgPath !== undefined){
        this.newdatalist[i].imgPath =  [...this.newdatalist[i].imgPath,...res1]
      }else {
        this.newdatalist[i].imgPath = res1
      }
        this.cd.detectChanges();
    })
  }
  //
  gotopay(){
    this.BaseUiService.showLoading('正在生成文件',0)
    for(let item of this.updatalist){
      for(let i of this.newdatalist){
        if(item.materialName == i.name){
          if(!!i.imgPath){
            i.imgPath.forEach(e => {
              console.log(e.unitGuid)
              item.annexFileLists.push(e.unitGuid)
            })
          }
        }
      }
    }
    console.log(JSON.stringify(this.updatalist))
    let p =  {
      items:JSON.stringify(this.updatalist),
      orderId:this.orderId
    }
    let that = this;
    this.HttpService.upgood(p).then(res =>{
      this.BaseUiService.hideLoading();
      if(res['code']==200){
        for(let i of  res['pdfImgPaths']){
          this.pdfImglist.push(this.HttpService.imgSrc() + i)
        }
        this.cd.detectChanges();
        setTimeout(()=>{
          that.isShowimg = true;
        },200)
        this.isShow = false
      }
    })
  }
}
